package com.smartad.Web;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import com.google.gson.Gson;
import com.smartad.common.MyConfig;
import com.smartad.nodes.NodeManager;

public class HttpRequestHandler {

	String _url = "";
	BufferedOutputStream _out = null;
	String _urlFilePath = "";

	public HttpRequestHandler(String url, BufferedOutputStream out) {
		_url = url;
		_out = out;

		int paramStart = 0;
		if ((paramStart = _url.indexOf("?")) >= 0) {
			_urlFilePath = _url.substring(0, paramStart);
		} else {
			_urlFilePath = _url;
			if(_urlFilePath.equals("/")) {
				_urlFilePath = "/index.html";
			}
		}
	}

	public void doGet() throws IOException {

		if (_urlFilePath.toLowerCase().endsWith(".json")) {
			doGetJson();
		} else {
			doGetFile();
		}
	}

	void doGetFile() throws IOException {

		FileInputStream fin = null;
		boolean fileExist = false;
		try {
			fin = new FileInputStream(MyConfig.getFileAbsolutePath("web/" + _urlFilePath));
			fileExist = true;
		} catch (Exception ex) {
			fileExist = false;
		}

		String ServerLine = "Server: Simple HTTP Server\r\n";
		String StatusLine = null;
		String ContentTypeLine = null;
		String ContentLengthLine = null;
		String ContentBody = null;

		String contentType = "text/html";
		if (_urlFilePath.endsWith(".js")) {
			contentType = "application/x-javascript";
		} else if (_urlFilePath.endsWith(".css")) {
			contentType = "text/css";
		} else if (_urlFilePath.endsWith(".png")) {
			contentType = "image/png";
		} else if (_urlFilePath.endsWith(".jpg")) {
			contentType = "image/jpg";
		} else if (_urlFilePath.endsWith(".gif")) {
			contentType = "image/gif";
		}

		if (fileExist) {
			StatusLine = "HTTP/1.1 200 OK\r\n";
			ContentTypeLine = "Content-type: " + contentType + "\r\n";
			ContentLengthLine = "Content-Length: "
					+ (new Integer(fin.available()).toString()) + "\r\n";
		} else {
			StatusLine = "HTTP/1.1 404 Not Found\r\n";
			ContentTypeLine = "Content-type: text/html\r\n";
			ContentBody = "<HTML>"
					+ "<HEAD><TITLE>404 Not Found</TITLE></HEAD>"
					+ "<BODY>404 Not Found" + "</BODY></HTML>";
			ContentLengthLine = "Content-Length: "
					+ (new Integer(ContentBody.length()).toString()) + "\r\n";
		}

		_out.write(StatusLine.getBytes());
		_out.write(ServerLine.getBytes());
		_out.write(ContentTypeLine.getBytes());
		_out.write(ContentLengthLine.getBytes());
		
		//_out.write("ETag:\"80966af4d767d01:0\"\r\n".getBytes());
		
		String gmt = getNowGMT();
		//_out.write(("Last-Modified: " + gmt + "\r\n").getBytes());
		_out.write(("Date: " + gmt + "\r\n").getBytes());
		// end of http header
		_out.write("\r\n".getBytes());

		if (fileExist) {

			byte[] buffer = new byte[1024];
			int bytes = 0;
			while ((bytes = fin.read(buffer)) != -1) {
				_out.write(buffer, 0, bytes);
			}

			fin.close();
		} else {
			_out.write(ContentBody.getBytes());
		}

		_out.flush();
	}

	void doGetJson() throws IOException {

		String ServerLine = "Server: Simple HTTP Server\r\n";
		String StatusLine = null;
		String ContentTypeLine = null;
		String ContentLengthLine = null;
		String ContentBody = null;

		switch (_urlFilePath.toLowerCase()) {
		case "/list.json":
			
			String json = new Gson().toJson(new NodeManager().getNodes());
			
			StatusLine = "HTTP/1.1 200 OK\r\n";
			ContentTypeLine = "Content-type: application/json; charset=utf-8\r\n";
			ContentBody = json;//"[{\"id\":\"1\",\"name\":\"aaa\"},{\"id\":\"2\",\"name\":\"bbb\"}]";
			ContentLengthLine = "Content-Length: "
					+ (new Integer(ContentBody.getBytes("UTF-8").length).toString()) + "\r\n";
			break;
		case "/save.json":
			
			StatusLine = "HTTP/1.1 200 OK\r\n";
			ContentTypeLine = "Content-type: text/html\r\n";
			ContentBody = "";
			ContentLengthLine = "Content-Length: "
					+ (new Integer(ContentBody.getBytes("UTF-8").length).toString()) + "\r\n";
			break;
		default:
			StatusLine = "HTTP/1.1 404 Not Found\r\n";
			ContentTypeLine = "Content-type: text/html\r\n";
			ContentBody = "<HTML>"
					+ "<HEAD><TITLE>404 Not Found</TITLE></HEAD>"
					+ "<BODY>404 Not Found" + "</BODY></HTML>";
			ContentLengthLine = "Content-Length: "
					+ (new Integer(ContentBody.length()).toString()) + "\r\n";
			break;
		}

		_out.write(StatusLine.getBytes());
		_out.write(ServerLine.getBytes());
		_out.write(ContentTypeLine.getBytes());
		_out.write(ContentLengthLine.getBytes());
		// end of http header
		_out.write("\r\n".getBytes());
		// http body
		_out.write(ContentBody.getBytes("UTF-8"));

		_out.flush();
	}

	String getNowGMT() {
		final Date currentTime = new Date();

		final SimpleDateFormat sdf = new SimpleDateFormat(
				"EEE, MMM d, yyyy hh:mm:ss a z", Locale.US);

		// Give it to me in GMT time.
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		String ret = sdf.format(currentTime);
		return ret;
	}
}
